﻿using Abp;
using Batman.Cms.Core.Models;
using Microsoft.AspNetCore.Hosting;
using System.Collections.Generic;
using System.Linq;

namespace Batman.Cms.Core.Configurations
{
    public class UpYunConfigurations
    {
        private static List<UpYunConfiguration> _configurations;

        private readonly IHostingEnvironment HostingEnvironment;

        public UpYunConfigurations(IHostingEnvironment hostingEnvironment)
        {
            HostingEnvironment = hostingEnvironment;
        }

        /// <summary>
        /// 默认使用第一个又拍云配置
        /// </summary>
        public UpYunConfiguration Default
        {
            get
            {
                var _default = GetConfigurations().FirstOrDefault();
                if (_default == null) throw new AbpException("请配置appsetting的又拍云信息");
                return _default;
            }
            private set { }
        }

        /// <summary>
        /// 又拍云在AppSetting.json中的固定字段名
        /// </summary>
        private static readonly string SectionName = "UPYun";

        /// <summary>
        /// 获取AppSetting.json中的又拍云配置
        /// </summary>
        /// <returns></returns>
        public List<UpYunConfiguration> GetConfigurations()
        {
            if (_configurations == null)
            {
                var configurationRoot = AppConfigurations.Default(HostingEnvironment);

                var section = configurationRoot.GetSection(SectionName);

                var children = section.GetChildren();

                _configurations = new List<UpYunConfiguration>();

                foreach (var child in children)
                {
                    var account = child.GetSection("Account").Value;
                    var password = child.GetSection("Password").Value;
                    var bucketname = child.GetSection("Bucketname").Value;
                    var domain = child.GetSection("Domain").Value;

                    _configurations.Add(new UpYunConfiguration(account, password, bucketname, domain));
                }
            }

            return _configurations;
        }
    }
}
